<script setup>
	//1.网络请求
	//2.Promise 应用

import { ref } from 'vue';
import { onPullDownRefresh,onShow } from '@dcloudio/uni-app'
	
	
	const bookList = ref([])
	const getBookList = async () => {
		uni.showLoading({title:'数据加载中...'})
		const res = await uni.request({
			method:'GET',
			url:'https://hmajax.itheima.net/api/books',
			data:{creator:'东华理工'}
		})
		console.log(res)
		//保存后端返回的数据
		bookList.value = res.data.data
		//关闭加载动画
		uni.hideLoading()
	}
	//页面显示，重新获取最新列表数据
	onShow(()=>{
		getBookList()
	})
	
	
	//下拉刷新
	onPullDownRefresh(async ()=>{
		//重新获取图书列表
		await getBookList()
		//停止下拉刷新动画
		uni.stopPullDownRefresh()
	})
	
	const deleteBook = async (id)=> {
		await uni.request({
			method:'DELETE',
			//路径参数，直接拼接到路径
			url:`https://hmajax.itheima.net/api/books/${id}`,
			data:{}
		})
		uni.showToast({title:'删除成功'})
		//删除成功，重新获取最新列表
		getBookList()
	}
</script>


<template>
	<navigator url="/pages/book-add/book-add">
		<button class="add-book-button" type="primary">新增图书</button>
	</navigator>
	
	<view>
		<view class="book-list">
			<view class="book-item row" v-for="item in bookList " :key="item.id">
				<image class="book-cover" src="/static/ic_public_cover.png"></image>
				<view class="book-info column">
					<text class="book-name">{{item.bookname}}</text>
					<text class="book-author">{{item.author}}</text>
					<text class="book-publisher">{{item.publisher}}</text>
					<view class="book-options row">
						<button class="book-options-button" type="primary" size="mini">查看</button>
						<button @click="deleteBook(item.id)" class="book-options-button" type="warn" size="mini">删除</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>


<style lang="scss">
	.add-book-button{
		background-color: $uni-color-primary;
		margin: 20rpx;
	}
	.book-list{
	   .book-item{
		  padding: 20rpx;
		  &:not(:last-child){
			  border-bottom: 1rpx solid #ddd;
		  }
	   }
	   .book-cover{
		  width: 200rpx;
		  height: 200rpx;
		  margin-right: 20rpx;
	   }
	   .book-options{
		  margin-top: auto;
	   }
	   .book-options-button{
		   margin: 0;
		   margin-right: 20rpx;
	   }
	}
</style>
